import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os

def mail(smtpServer,
         gmail_user,
         gmail_pwd,
         to,
         subject,
         text,
         attach):
   """
      An example
   result=mail("smtp.gmail.com",#Smtp server
        "keremtiryaki@gmail.com",#gmail account
        "*****",#gmail account pass
        "keremtiryaki@gmail.com",#to
        "Hello from python!",#subject
        "PySecureMail",#content
        "myfile")#attachment
   print result
   
   """
   try:
      msg = MIMEMultipart()

      msg['From'] = gmail_user
      msg['To'] = to
      msg['Subject'] = subject

      msg.attach(MIMEText(text))

      part = MIMEBase('application', 'octet-stream')
      part.set_payload(open(attach, 'rb').read())
      Encoders.encode_base64(part)
      part.add_header('Content-Disposition',
              'attachment; filename="%s"' % os.path.basename(attach))
      msg.attach(part)

      mailServer = smtplib.SMTP(smtpServer, 587)
      
      
      mailServer.ehlo()
      mailServer.starttls()
      mailServer.ehlo()
      mailServer.login(gmail_user, gmail_pwd)
      mailServer.sendmail(gmail_user, to, msg.as_string())
      # Should be mailServer.quit(), but that crashes...
      mailServer.close()
      return "Sent Successfully"
   except:
      return "An Error Occured, Please Check The Account Username & Password"
